<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>202-迭代</title>

<script src="/lib/require/index.js"></script>
<script src="/lib/jquery/index.js"></script>

<!-- 改为引入外部样式 -->
<link rel="stylesheet" href="/css/custom.css">

<!-- Loading mathjax macro -->
<!-- Load mathjax -->
    <script src="/lib/mathjax/index.js"></script>
    <!-- MathJax configuration -->
    <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ['$','$'], ["\\(","\\)"] ],
            displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
            processEscapes: true,
            processEnvironments: true
        },
        // Center justify equations in code and markdown cells. Elsewhere
        // we use CSS to left justify single line equations in code cells.
        displayAlign: 'center',
        "HTML-CSS": {
            styles: {'.MathJax_Display': {"margin": 0}},
            linebreaks: { automatic: true }
        }
    });
    </script>
    <!-- End of mathjax configuration --></head>
<body>
<div class="toc">
<ul>
                        
                        
                        <li class="toc-li-2">
                            <a href="#迭代">迭代</a>
                        </li>
                    
                
            
            
            
            
            
            
            
            
            
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#容器（container)">容器（container)</a>
                        </li>
                    
                
            
            
            
            
            
            
            
            
            
            
            
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#可迭代对象">可迭代对象</a>
                        </li>
                    
                
            
            
            
            
            
            
            
            
            
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#迭代器(Iterators)">迭代器(Iterators)</a>
                        </li>
                    
                
            
            
            
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#itertools模块">itertools模块</a>
                        </li>
                    
                
            
            
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#生成器(generator)">生成器(generator)</a>
                        </li>
                    
                
            
            
            
            
            
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#list解析式">list解析式</a>
                        </li>
                    
                
            
            
            
            
            
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#dict解析式">dict解析式</a>
                        </li>
                    
                
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#生成器表达式">生成器表达式</a>
                        </li>
                    
                
            
            
            
            
            
            
            
                        
                        
                        <li class="toc-li-2">
                            <a href="#并行迭代">并行迭代</a>
                        </li>
                    
                
            
            
            
                        
                        
                        <li class="toc-li-3">
                            <a href="#zip(iter1-[,iter2-[...]])">zip(iter1 [,iter2 [...]])</a>
                        </li>
                    
                
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#问题一：多个矩阵元素互换">问题一：多个矩阵元素互换</a>
                        </li>
                    
                
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#问题二：列表求和">问题二：列表求和</a>
                        </li>
                    
                
            
            
                        
                        
                        <li class="toc-li-4">
                            <a href="#问题三：字典键值互换">问题三：字典键值互换</a>
                        </li>
                    
                
            </ul>
</div>
  <div tabindex="-1" id="notebook" class="border-box-sizing">
    <div class="container" id="notebook-container">

<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[2]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 打印所有单行变量</span>
<span class="kn">from</span> <span class="nn">IPython.core.interactiveshell</span> <span class="k">import</span> <span class="n">InteractiveShell</span>
<span class="n">InteractiveShell</span><span class="o">.</span><span class="n">ast_node_interactivity</span> <span class="o">=</span> <span class="s1">&#39;all&#39;</span>
</pre></div>

</div>
</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="&#36845;&#20195;">&#36845;&#20195;<a class="anchor-link" href="#&#36845;&#20195;">&#182;</a></h2><p>在使用Python的过程中，很容易混淆如下几个关联的概念：</p>
<ul>
<li>容器(container)</li>
<li>可迭代对象(Iterable)</li>
<li>迭代器(Iterator)</li>
<li>生成器(generator)</li>
<li>list, set, dict解析式</li>
<li>生成器表达式</li>
</ul>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="&#23481;&#22120;&#65288;container)">&#23481;&#22120;&#65288;container)<a class="anchor-link" href="#&#23481;&#22120;&#65288;container)">&#182;</a></h3><p>容器是用来储存元素的一种数据结构，它支持隶属测试，容器将所有数据保存在内存中，在Python中典型的容器有：</p>
<ul>
<li>list， deque, ...</li>
<li>set，frozesets，...</li>
<li>dict, defaultdict, OrderedDict, Counter, ...</li>
<li>tuple, namedtuple, ...</li>
<li>str</li>
</ul>
<p>用in，not in判断是否存在，字典容器通过检查是否包含键来进行判断，字符串通过检查是否包含某个子串来判断</p>
<blockquote><p><strong>注意</strong>：并非所有的容器都是可迭代对象。</p>
</blockquote>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[3]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="mi">1</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>      <span class="c1"># --&gt;</span>
<span class="mi">4</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>      <span class="c1"># --&gt;</span>
<span class="mi">4</span> <span class="ow">not</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[3]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>True</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[3]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>False</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[3]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>True</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="&#21487;&#36845;&#20195;&#23545;&#35937;">&#21487;&#36845;&#20195;&#23545;&#35937;<a class="anchor-link" href="#&#21487;&#36845;&#20195;&#23545;&#35937;">&#182;</a></h3><p>正如前面所提到的，大部分容器都是可迭代的，但是还有其他一些对象也可以迭代，例如，文件对象以及管道对象等等</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[4]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="n">y</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>

<span class="nb">next</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
<span class="nb">next</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>  <span class="c1"># --&gt;</span>

<span class="nb">type</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
<span class="nb">type</span><span class="p">(</span><span class="n">y</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[4]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>1</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[4]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>2</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[4]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>list</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[4]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>list_iterator</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>在这里，x是可迭代对象。而y是迭代器，可以从可迭代对象x中获取值。</p>
<blockquote><p><strong>注意</strong>：可迭代的类中，一般实现以下两个方法，<code>__iter__()</code>以及<code>__next()__</code>方法，<code>__iter__()</code>方法返回self。</p>
</blockquote>
<p>实际调用过程如下：</p>
<p><img src="http://upload-images.jianshu.io/upload_images/1677721-9453ca206b60475d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt=""></p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="&#36845;&#20195;&#22120;(Iterators)">&#36845;&#20195;&#22120;(Iterators)<a class="anchor-link" href="#&#36845;&#20195;&#22120;(Iterators)">&#182;</a></h3><ul>
<li>迭代器是一个可以记住遍历的位置的对象。</li>
<li>迭代器对象从第一个元素开始访问，直到所有的元素被访问完结束。</li>
<li>迭代器只能往前不会后退。</li>
<li>迭代器有两个基本的方法：<code>__iter__()</code> 和 <code>__next__()</code></li>
</ul>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="itertools&#27169;&#22359;">itertools&#27169;&#22359;<a class="anchor-link" href="#itertools&#27169;&#22359;">&#182;</a></h4>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[5]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">itertools</span> <span class="k">import</span> <span class="n">count</span>
<span class="n">counter</span> <span class="o">=</span> <span class="n">count</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="mi">13</span><span class="p">)</span>

<span class="nb">next</span><span class="p">(</span><span class="n">counter</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
<span class="nb">next</span><span class="p">(</span><span class="n">counter</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[5]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>13</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[5]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>14</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>无限序列：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[6]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">itertools</span> <span class="k">import</span> <span class="n">cycle</span>
<span class="n">colors</span> <span class="o">=</span> <span class="n">cycle</span><span class="p">([</span><span class="s2">&quot;red&quot;</span><span class="p">,</span><span class="s2">&quot;white&quot;</span><span class="p">,</span><span class="s2">&quot;blue&quot;</span><span class="p">])</span>

<span class="nb">next</span><span class="p">(</span><span class="n">colors</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
<span class="nb">next</span><span class="p">(</span><span class="n">colors</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
<span class="nb">next</span><span class="p">(</span><span class="n">colors</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
<span class="nb">next</span><span class="p">(</span><span class="n">colors</span><span class="p">)</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[6]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>&#39;red&#39;</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[6]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>&#39;white&#39;</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[6]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>&#39;blue&#39;</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[6]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>&#39;red&#39;</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>无限序列生成有限序列：</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[7]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="kn">from</span> <span class="nn">itertools</span> <span class="k">import</span> <span class="n">islice</span>
<span class="n">colors</span> <span class="o">=</span> <span class="n">cycle</span><span class="p">([</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="s1">&#39;white&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">])</span>    <span class="c1"># infinite</span>
<span class="n">limited</span> <span class="o">=</span> <span class="n">islice</span><span class="p">(</span><span class="n">colors</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>              <span class="c1"># finite</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">limited</span><span class="p">:</span>       <span class="c1"># so safe to use for-loop on</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt"></div>


<div class="output_subarea output_stream output_stdout output_text">
<pre>red
white
blue
red
</pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="&#29983;&#25104;&#22120;(generator)">&#29983;&#25104;&#22120;(generator)<a class="anchor-link" href="#&#29983;&#25104;&#22120;(generator)">&#182;</a></h3><p>带有<code>yield</code>关键字的的函数在Python中被称之为 generator(生成器)。
一个函数或者子程序都只能return一次，但是一个生成器能暂停执行并返回一个中间的结果。</p>
<blockquote><p>生成器其实就是一种特殊的迭代器</p>
</blockquote>
<p>生成器的另一个优点就是无须将对象的所有元素都存入内存之后，才开始进行操作。生成器仅在迭代至某个元素时才会将该元素放入内存，而在这之前或之后，元素可以不存在或者被销毁。这个特点使得它特别适合用于遍历一些巨大的或是无限的类序列对象，EG. 大文件/大集合/大字典/斐波那契数列等。这个特点被称为 延迟计算 或 惰性求值(Lazy evaluation)，可以有效的节省内存。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="list&#35299;&#26512;&#24335;">list&#35299;&#26512;&#24335;<a class="anchor-link" href="#list&#35299;&#26512;&#24335;">&#182;</a></h3>
<pre><code>[expr for iter_var in iterable]    # 最终生成一个列表[expr]
[expr for iter_var in iterable if cond_expr]</code></pre>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[8]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="p">[(</span><span class="n">x</span><span class="o">+</span><span class="mi">1</span><span class="p">,</span> <span class="n">y</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span> 
<span class="n">x</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[8]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[9]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">y</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="o">+</span><span class="mi">10</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="k">if</span> <span class="n">x</span><span class="o">&gt;</span><span class="mi">5</span><span class="p">]</span>
<span class="n">y</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[9]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[16, 17, 18, 19]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<blockquote><p>还有集合解析，类似列表解析，区别在于结果满足集合的特性</p>
</blockquote>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="dict&#35299;&#26512;&#24335;">dict&#35299;&#26512;&#24335;<a class="anchor-link" href="#dict&#35299;&#26512;&#24335;">&#182;</a></h3>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[10]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;a&quot;</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;b&quot;</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s2">&quot;c&quot;</span><span class="p">:</span><span class="mi">3</span><span class="p">,</span> <span class="s2">&quot;d&quot;</span><span class="p">:</span><span class="mi">4</span><span class="p">}</span>
<span class="n">y</span> <span class="o">=</span> <span class="p">{</span><span class="n">v</span><span class="p">:</span> <span class="n">k</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">x</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span>
<span class="n">y</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[10]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;, 4: &#39;d&#39;}</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h3 id="&#29983;&#25104;&#22120;&#34920;&#36798;&#24335;">&#29983;&#25104;&#22120;&#34920;&#36798;&#24335;<a class="anchor-link" href="#&#29983;&#25104;&#22120;&#34920;&#36798;&#24335;">&#182;</a></h3>
<pre><code>(expr for iter_var in iterable)
(expr for iter_var in iterable if cond_expr)</code></pre>
<p>当序列过长，而每次只需要获取一个元素时，应当考虑使用生成器表达式而不是列表解析。生成器表达式的语法和列表解析一样，只不过生成器表达式是被<code>()</code>括起来的，而不是<code>[]</code></p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[11]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">y</span> <span class="o">=</span> <span class="p">(</span><span class="n">x</span><span class="o">+</span><span class="mi">10</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="k">if</span> <span class="n">x</span><span class="o">&gt;</span><span class="mi">7</span><span class="p">)</span>
<span class="n">y</span>  <span class="c1"># --&gt;</span>

<span class="n">y</span><span class="o">.</span><span class="fm">__next__</span><span class="p">()</span>  <span class="c1"># --&gt;</span>
<span class="n">y</span><span class="o">.</span><span class="fm">__next__</span><span class="p">()</span>  <span class="c1"># --&gt;</span>
<span class="n">y</span><span class="o">.</span><span class="fm">__next__</span><span class="p">()</span>  <span class="c1"># &gt;_&lt; StopIteration</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[11]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>&lt;generator object &lt;genexpr&gt; at 0x7f75c84bfdb0&gt;</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[11]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>18</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[11]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>19</pre>
</div>

</div>

<div class="output_area">

<div class="prompt"></div>


<div class="output_subarea output_text output_error">
<pre>
<span class="ansi-red-fg">---------------------------------------------------------------------------</span>
<span class="ansi-red-fg">StopIteration</span>                             Traceback (most recent call last)
<span class="ansi-green-fg">&lt;ipython-input-11-5792f45bb622&gt;</span> in <span class="ansi-cyan-fg">&lt;module&gt;</span><span class="ansi-blue-fg">()</span>
<span class="ansi-green-intense-fg ansi-bold">      4</span> y<span class="ansi-blue-fg">.</span>__next__<span class="ansi-blue-fg">(</span><span class="ansi-blue-fg">)</span>  <span class="ansi-red-fg"># --&gt;</span>
<span class="ansi-green-intense-fg ansi-bold">      5</span> y<span class="ansi-blue-fg">.</span>__next__<span class="ansi-blue-fg">(</span><span class="ansi-blue-fg">)</span>  <span class="ansi-red-fg"># --&gt;</span>
<span class="ansi-green-fg">----&gt; 6</span><span class="ansi-red-fg"> </span>y<span class="ansi-blue-fg">.</span>__next__<span class="ansi-blue-fg">(</span><span class="ansi-blue-fg">)</span>  <span class="ansi-red-fg"># --&gt; 报错</span>

<span class="ansi-red-fg">StopIteration</span>: </pre>
</div>
</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>生成器表达式并不真正创建数字列表， 而是返回一个生成器，这个生成器在每次计算出一个条目后，把这个条目“产生”(yield)出来。 生成器表达式使用了“惰性计算”(lazy evaluation)，只有在检索时才被赋值 (evaluated)，所以在列表比较长的情况下使用内存上更有效。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h2 id="&#24182;&#34892;&#36845;&#20195;">&#24182;&#34892;&#36845;&#20195;<a class="anchor-link" href="#&#24182;&#34892;&#36845;&#20195;">&#182;</a></h2><p>迭代两个以上的集合</p>
<h3 id="zip(iter1-[,iter2-[...]])">zip(iter1 [,iter2 [...]])<a class="anchor-link" href="#zip(iter1-[,iter2-[...]])">&#182;</a></h3><h4 id="&#38382;&#39064;&#19968;&#65306;&#22810;&#20010;&#30697;&#38453;&#20803;&#32032;&#20114;&#25442;">&#38382;&#39064;&#19968;&#65306;&#22810;&#20010;&#30697;&#38453;&#20803;&#32032;&#20114;&#25442;<a class="anchor-link" href="#&#38382;&#39064;&#19968;&#65306;&#22810;&#20010;&#30697;&#38453;&#20803;&#32032;&#20114;&#25442;">&#182;</a></h4>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[14]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="n">y</span> <span class="o">=</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="n">z</span> <span class="o">=</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">]</span>
<span class="n">xyz</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span><span class="p">))</span>
<span class="n">xyz</span>  <span class="c1"># --&gt;</span>

<span class="n">zyx</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="n">xyz</span><span class="p">))</span>   <span class="c1"># 参数加*解压</span>
<span class="n">zyx</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[14]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[(1, 4, 7), (2, 5, 8), (3, 6, 9)]</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[14]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[(1, 2, 3), (4, 5, 6), (7, 8, 9)]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="&#38382;&#39064;&#20108;&#65306;&#21015;&#34920;&#27714;&#21644;">&#38382;&#39064;&#20108;&#65306;&#21015;&#34920;&#27714;&#21644;<a class="anchor-link" href="#&#38382;&#39064;&#20108;&#65306;&#21015;&#34920;&#27714;&#21644;">&#182;</a></h4><p>有两个列表，分别是：a = [1, 2, 3, 4, 5], b = [9, 8, 7, 6, 5]，要计算这两个列表中对应元素的和。</p>

</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[16]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1">#方法一：</span>
<span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>
<span class="n">b</span> <span class="o">=</span> <span class="p">[</span><span class="mi">9</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>
<span class="n">c</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">)):</span>
    <span class="n">c</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">b</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>

<span class="n">c</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[16]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[10, 10, 10, 10, 10]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[17]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 方法二：</span>
<span class="n">d</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">):</span>
    <span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span> <span class="o">+</span> <span class="n">y</span><span class="p">)</span>

<span class="n">d</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[17]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[10, 10, 10, 10, 10]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[18]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 用列表解析：</span>

<span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">+</span><span class="n">b</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">))]</span>
<span class="n">x</span>  <span class="c1"># --&gt;</span>

<span class="n">y</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="o">+</span><span class="n">y</span> <span class="k">for</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">)]</span>
<span class="n">y</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[18]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[10, 10, 10, 10, 10]</pre>
</div>

</div>

<div class="output_area">

<div class="prompt output_prompt">Out[18]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>[10, 10, 10, 10, 10]</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing text_cell rendered"><div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h4 id="&#38382;&#39064;&#19977;&#65306;&#23383;&#20856;&#38190;&#20540;&#20114;&#25442;">&#38382;&#39064;&#19977;&#65306;&#23383;&#20856;&#38190;&#20540;&#20114;&#25442;<a class="anchor-link" href="#&#38382;&#39064;&#19977;&#65306;&#23383;&#20856;&#38190;&#20540;&#20114;&#25442;">&#182;</a></h4>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[20]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 用for循环:</span>
<span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">:</span><span class="mi">3</span><span class="p">}</span>
<span class="n">m</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
    <span class="n">m</span><span class="p">[</span><span class="n">v</span><span class="p">]</span> <span class="o">=</span> <span class="n">k</span>  <span class="c1"># 以v为key,以k为values添加键值对</span>

<span class="n">m</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[20]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;}</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[22]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 因为字典有items方法,而zip只能获得key:</span>
<span class="n">x</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">values</span><span class="p">(),</span><span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">()))</span>
<span class="n">x</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[22]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;}</pre>
</div>

</div>

</div>
</div>

</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In&nbsp;[23]:</div>
<div class="inner_cell">
    <div class="input_area">
<div class=" highlight hl-ipython3"><pre><span></span><span class="c1"># 用dict解析:</span>
<span class="n">y</span> <span class="o">=</span> <span class="p">{</span><span class="n">v</span><span class="p">:</span><span class="n">k</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span>
<span class="n">y</span>  <span class="c1"># --&gt;</span>
</pre></div>

</div>
</div>
</div>

<div class="output_wrapper">
<div class="output">


<div class="output_area">

<div class="prompt output_prompt">Out[23]:</div>




<div class="output_text output_subarea output_execute_result">
<pre>{1: &#39;a&#39;, 2: &#39;b&#39;, 3: &#39;c&#39;}</pre>
</div>

</div>

</div>
</div>

</div>
    </div>
  </div>
</body>

 


</html>
